<script setup lang="ts">
import { SysRole } from "@/api/user/type/user"
import { roleUpdateApi } from "@/api/user/role"
import MenuTree from "./menu-tree.vue"
import { readonly, ref, unref, watch } from "vue"
import { ElMessage } from "element-plus"

const display = ref<boolean>(false)
const props = defineProps(["role"])
const roleMenuRef = ref()
const editRole = ref({
  menuIds: [] as string[]
} as SysRole)

watch(
  () => props.role,
  (newv) => {
    editRole.value = newv
    editRole.value.menuIds = [...readonly(newv.menuIds)]
  }
)

const open = () => {
  display.value = true
}

const close = () => {
  display.value = false
  roleMenuRef.value.close()
}

/** 菜单ID */
const edmit = () => {
  editRole.value.menuIds = roleMenuRef.value.menuId
  roleUpdateApi(unref(editRole)).then((res) => {
    const { code } = res
    if (code === 200) {
      ElMessage({
        type: "success",
        message: "角色修改成功"
      })
      close()
    }
  })
}

defineExpose({
  open,
  close
})
</script>

<template>
  <el-drawer v-model="display" @close="close" title="编辑角色">
    <el-form :model="editRole" label-width="70" size="large">
      <el-form-item label="ID">
        <el-input v-model="editRole.id" disabled />
      </el-form-item>
      <el-form-item label="角色名称">
        <el-input v-model="editRole.role" />
      </el-form-item>
      <el-form-item label="描述">
        <el-input v-model="editRole.desc" type="textarea" :rows="4" placeholder="角色描述" />
      </el-form-item>
      <el-form-item label="权限">
        <MenuTree :initMenuId="editRole.menuIds" ref="roleMenuRef" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="edmit" size="large">修 改</el-button>
      </el-form-item>
    </el-form>
  </el-drawer>
</template>
